package com.ycl.bookstore.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ycl.bookstore.common.Result;
import com.ycl.bookstore.mapper.BalanceMapper;
import com.ycl.bookstore.pojo.RechargeRecord;
import com.ycl.bookstore.service.RechargeRecordService;
import com.ycl.bookstore.mapper.RechargeRecordMapper;
import com.ycl.bookstore.utils.MyThreadLocal;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.ycl.bookstore.utils.RedisConstants.RECORD_LIST_KEY;

/**
 *
 */
@Service
public class RechargeRecordServiceImpl extends ServiceImpl<RechargeRecordMapper, RechargeRecord>
        implements RechargeRecordService {

    //充值信息总数
    Long total = null;

    @Resource
    private BalanceMapper balanceMapper;

    @Resource
    private RechargeRecordMapper rechargeRecordMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 得到充值信息列表
     *
     * @param pageNo
     * @param pageSize
     * @param recordId
     * @return
     */
    @Override
    public Result getListByPage(Long pageNo, Long pageSize, String recordId) {
        //获取用户的id
        Long userId = MyThreadLocal.getUser().getId();
        String nickName = MyThreadLocal.getUser().getNickName();
        Map<String, Object> data = new HashMap<>();
        String key = RECORD_LIST_KEY + userId;
        //充值信息列表
        List<RechargeRecord> recordList = new LinkedList<>();
        // 如果redis中不存在充值信息列表
        if (stringRedisTemplate.opsForZSet().size(key) < 1) {
            // 从数据库查询再存入数据库中
            createRecordByRedis(key, nickName);
        }
        // 但用户进行查询时
        if (recordId != null) {
            Long score = Long.valueOf(recordId);
            // 根据充值记录查询列表
            Set<String> set = stringRedisTemplate.opsForZSet().rangeByScore(key, score, score);
            // 查询总数
            total = Long.valueOf(set.size());
            for (String s : set) {
                RechargeRecord record = JSONUtil.toBean(s, RechargeRecord.class);
                record.setNickName(nickName);
                recordList.add(record);
            }
        } else {
            recordList = getRecordList(userId, pageNo, pageSize);
            total = (long) recordList.size();
        }
        data.put("total", total);
        data.put("recordList", recordList);
        return Result.success(data);
    }

    /**
     * 删除充值信息记录
     * @param recordId
     * @return
     */
    @Override
    public Result deleteRecord(String recordId) {
        //获取用户id
        Long userId = MyThreadLocal.getUser().getId();
        // 修改充值信息记录的status
        int count = rechargeRecordMapper.updateByStatus(0, recordId);
        // 删除redis中缓存的信息
        Long score=Long.valueOf(recordId);
        count += stringRedisTemplate.opsForZSet().removeRangeByScore(RECORD_LIST_KEY + userId, score, score);
        if(count<2){
            return Result.fail("删除失败");
        }
        return Result.success();
    }

    public void createRecordByRedis(String key, String nickName) {
        LambdaQueryWrapper<RechargeRecord> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(RechargeRecord::getStatus,1);
        List<RechargeRecord> rechargeRecords = rechargeRecordMapper.selectList(wrapper);
        for (RechargeRecord rechargeRecord : rechargeRecords) {
            rechargeRecord.setNickName(nickName);
            Long score = Long.valueOf(rechargeRecord.getRecordId());
            // 从充值记录中取出每一条信息 然后转化为json  存入redis中
            stringRedisTemplate.opsForZSet().add(key, JSONUtil.toJsonStr(rechargeRecord), score);
        }
    }

    public List<RechargeRecord> getRecordList(Long userId, Long pageNo, Long pageSize) {
        Long start = (pageNo - 1) * pageSize;
        Long edd = start + pageSize - 1;
        //redis分页查询
        Set<String> recordSet = stringRedisTemplate.opsForZSet().range(RECORD_LIST_KEY + userId, start, edd);
        List<RechargeRecord> recordList = new LinkedList<>();
        String nickName = MyThreadLocal.getUser().getNickName();
        for (String s : recordSet) {
            RechargeRecord record = JSONUtil.toBean(s, RechargeRecord.class);
            record.setNickName(nickName);
            recordList.add(record);
        }
        return recordList;
    }
}




